<template>
  <div class="category-level2">
    <!-- 查询区域 -->
    <div class="search-bar">
      <el-input v-model="searchName" placeholder="二级分类名称" style="width: 200px; margin-right: 10px;" />
      <el-select v-model="selectedParentId" placeholder="所属一级分类" style="width: 200px; margin-right: 10px;">
        <el-option v-for="item in parentOptions" :key="item.id" :label="item.categoryName" :value="item.id" />
      </el-select>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">重置</el-button>
      <el-button type="primary" style="float: right;" @click="handleAdd">+ 添加二级分类</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table :data="tableData" :loading="loading" style="width: 100%; margin-top: 20px;">
      <el-table-column prop="categoryName" label="二级分类名称" />
      <el-table-column prop="parentCategoryName" label="所属一级分类" />
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      v-model:current-page="currentPage"
      :page-size="pageSize"
      :total="total"
      layout="prev, pager, next, jumper"
      style="margin-top: 20px; text-align: right;"
      @current-change="handlePageChange"
    />

    <!-- 编辑/新增弹窗 -->
    <el-dialog v-model="editDialogVisible" :title="editForm.id ? '编辑' : '添加二级分类'" width="400px">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="二级分类名称">
          <el-input v-model="editForm.categoryName" placeholder="请输入二级分类名称" />
        </el-form-item>
        <el-form-item label="所属一级分类">
          <el-select v-model="editForm.parentId" placeholder="请选择一级分类">
            <el-option v-for="item in parentOptions" :key="item.id" :label="item.categoryName" :value="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEditConfirm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 删除弹窗 -->
    <el-dialog v-model="deleteDialogVisible" title="删除" width="400px">
      <div>您确定要删除"{{ deleteRow?.categoryName }}"二级分类吗？</div>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleDeleteConfirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
console.log('CategoryLevel2 加载了');
import { ref, onMounted } from 'vue'
import { fetchCategoryLevel2, addCategoryLevel2, updateCategoryLevel2, deleteCategoryLevel2, fetchCategoryLevel1 } from '@/api/safetyCategory'
import { ElMessage } from 'element-plus'

const searchName = ref('')
const selectedParentId = ref()
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])
const loading = ref(false)
const parentOptions = ref([])

const editDialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const editForm = ref({
  id: null,
  categoryName: '',
  parentId: null
})
const deleteRow = ref(null)

const fetchParentOptions = async () => {
  const res = await fetchCategoryLevel1({})
  parentOptions.value = res.data.data?.records || []
  console.log('fetchParentOptions parentOptions:', parentOptions.value)
}

const fetchData = async () => {
  loading.value = true
  try {
    const res = await fetchCategoryLevel2({
      name: searchName.value,
      parentId: selectedParentId.value,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })
    const parentMap = Object.fromEntries((parentOptions.value || []).map(item => [String(item.id), item.categoryName]))
    console.log('parentOptions', parentOptions.value)
    console.log('parentMap', parentMap)
    const records = res.data.data?.records || []
    tableData.value = records.map(item => ({
      ...item,
      parentCategoryName: parentMap[String(item.parentId)] || ''
    }))
    console.log('tableData', tableData.value)
    total.value = res.data.data?.total || 0
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  if (!selectedParentId.value) {
    ElMessage.warning('请先选择所属一级分类');
    return;
  }
  currentPage.value = 1;
  fetchData();
}

function handleReset() {
  searchName.value = ''
  selectedParentId.value = undefined
  currentPage.value = 1
  fetchData()
}

function handleAdd() {
  editForm.value = { id: null, categoryName: '', parentId: null }
  editDialogVisible.value = true
}

function handleEdit(row) {
  editForm.value = {
    id: row.id,
    categoryName: row.categoryName,
    parentId: row.parentId
  }
  editDialogVisible.value = true
}

async function handleEditConfirm() {
  loading.value = true
  try {
    if (editForm.value.id) {
      await updateCategoryLevel2(editForm.value)
    } else {
      await addCategoryLevel2(editForm.value)
    }
    editDialogVisible.value = false
    fetchData()
  } finally {
    loading.value = false
  }
}

function handleDelete(row) {
  deleteRow.value = row
  deleteDialogVisible.value = true
}

async function handleDeleteConfirm() {
  loading.value = true
  try {
    await deleteCategoryLevel2(deleteRow.value.id)
    deleteDialogVisible.value = false
    fetchData()
  } finally {
    loading.value = false
  }
}

function handlePageChange(page) {
  currentPage.value = page
  fetchData()
}

onMounted(async () => {
  console.log('onMounted start')
  await fetchParentOptions()
  console.log('after fetchParentOptions')
  fetchData()
})
</script>

<style scoped>
.category-level2 {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
}
.search-bar {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}
</style> 